package com.java.zhuiyun.api.task.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.zhuiyun.api.playerinformation.entity.PlayerInformation;
import com.java.zhuiyun.api.playerinformation.mapper.PlayerInformationMapper;
import com.java.zhuiyun.api.playerinformation.service.PlayerInformationService;
import com.java.zhuiyun.api.task.entity.Task;
import com.java.zhuiyun.api.task.mapper.TaskMapper;
import com.java.zhuiyun.api.task.service.ITaskService;
import com.java.zhuiyun.usertask.entity.UserTask;
import com.java.zhuiyun.usertask.mapper.UserTaskMapper;
import com.java.zhuiyun.usertask.service.IUserTaskService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName TaskServiceImpl
 * @Description TODO
 * @Author xy
 * @Date 2023/9/17 21:16
 **/
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Resource
    private IUserTaskService userTaskService;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private PlayerInformationMapper playerInformationMapper;

    /**
    * @Author xy
    * @Description todo 任务管理的添加修改方法（后台管理）
    * @Date 2023/10/15 18:44
    * @Return boolean 返回类型
    * @param task 任务实体类
    */
    @Override
    public boolean saveTask(Task task) {
        Date now = new Date();

        if (task.getId() == null) {
            // 创建任务并保存
            task.setCreateTime(now);
            save(task);

            // 获取刚刚插入的任务的ID
            Integer taskId = task.getId();

            // 获取所有用户列表，将任务发布给所有用户
            List<PlayerInformation> playerInformations = playerInformationMapper.selectList(null);
            for (PlayerInformation playerInformation : playerInformations) {
                UserTask userTask = new UserTask();
                // 使用刚刚获取的任务ID
                userTask.setTaskid(taskId);
                userTask.setUserid(playerInformation.getId());
                // 创建任务与用户的关联
                userTaskService.save(userTask);
            }

            return true;
        }else {
            // 更新任务信息
            task.setUpdateTime(now);
            updateById(task);
            return true;
        }
    }
}
